﻿using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace SharpSoft.Web
{
    /// <summary>
    /// 默认的WebSocket消息服务
    /// </summary>
    public class wsMsgService
    {
        private object asyncstate = new object();
        private Dictionary<WebSocket, string> clients = new Dictionary<WebSocket, string>();
        public async Task ClientAccepted(WebSocket client, string guid)
        {
            lock (asyncstate)
            {
                clients.Add(client, guid);
            }

            await receiveWhile(client);
        }
        CancellationToken ct = new CancellationToken();

        private async Task receiveWhile(WebSocket client)
        {
            while (client.State == WebSocketState.Open)
            {
                try
                {
                    ArraySegment<byte> buf = new ArraySegment<byte>(new byte[4096]);
                    WebSocketReceiveResult result;
                    MemoryStream ms = new MemoryStream(4096);
                    do
                    {
                        result = await client.ReceiveAsync(buf, ct);
                        if (result.MessageType == WebSocketMessageType.Close)
                        {
                            await client.CloseAsync(WebSocketCloseStatus.Empty, "", CancellationToken.None);

                            break;
                        }
                        ms.Write(buf.Array, 0, result.Count);
                    } while (!result.EndOfMessage);
                    MessageReceived?.Invoke(client, System.Text.Encoding.UTF8.GetString(ms.ToArray()));
                }
                catch (Exception ex)
                {
                    Thread.Sleep(500);
                }


            }
            if (client.State == WebSocketState.Closed)
            {
                lock (asyncstate)
                {
                    clients.Remove(client);
                }
            }
        }
        /// <summary>
        /// 向客户端发送消息
        /// </summary>
        /// <param name="msg">消息内容</param>
        /// <param name="key">客户端标识，为null表示向所有已连接的客户端发送</param>
        public void Send(string msg, string key)
        {
            var buf = System.Text.Encoding.UTF8.GetBytes(msg);
            lock (asyncstate)
            {
                if (key == null)
                {
                    foreach (var item in clients)
                    {
                        item.Key.SendAsync(new ArraySegment<byte>(buf), WebSocketMessageType.Text, true, CancellationToken.None).Start();
                    }
                }
                else
                {
                    foreach (var item in clients)
                    {
                        if (item.Value.ToLower() == key.ToLower())
                        {
                            item.Key.SendAsync(new ArraySegment<byte>(buf), WebSocketMessageType.Text, true, CancellationToken.None);
                        }
                    }
                }

            }

        }

        public event wsMessageReceived MessageReceived;
    }

    public delegate void wsMessageReceived(WebSocket wsclient, string msg);
}
